using Game.Networking;
using Game.Networking.Utils;
using MoonSharp.Interpreter;
using MoonSharp.Interpreter.Debugging;
using NaughtyAttributes;
using RoslynCSharp;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Game {
	public class RoslynScriptRunner : MonoBehaviour {
		[TextArea]
		public string ScriptText;

		public AssemblyReferenceAsset[] AssemblyReferences;

		ScriptDomain _domain = null;
		ShipAPI _api;
		ScriptType _type;
		ScriptProxy _mainObjProxy;
		GlobalData _global;

		void Start () {
			if ( !NetworkOptions.StartServer ) {
				return;
			}
			InitScripting();
			_mainObjProxy.Call("Start");
		}

		private void Update() {
			if ( _mainObjProxy != null ) {
				_global.Time = ServerGameManager.Time;
				_mainObjProxy.Call("Update", Time.deltaTime);
				//UnityEngine.ve
			}
		}

		void InitScripting() {
			_api = GetComponent<ShipAPI>();
			_global = new GlobalData();

			_domain = ScriptDomain.CreateDomain($"ScriptingDomain_{Random.Range(0, 1000)}", true);
			foreach ( AssemblyReferenceAsset reference in AssemblyReferences ) {
				_domain.RoslynCompilerService.ReferenceAssemblies.Add(reference);
			}
			RecompileScript();
		}

		[Button("Recompile Script", EButtonEnableMode.Playmode)]
		void RecompileScript() {
			if ( _domain == null ) {
				return;
			}
			if ( !NetworkOptions.StartServer ) {
				return;
			}
			
			_type = _domain.CompileAndLoadMainSource(ScriptText, ScriptSecurityMode.UseSettings);
			_mainObjProxy = _type.CreateInstance();
			_mainObjProxy.Fields.SetValue("ShipAPI", _api);
			_mainObjProxy.Fields.SetValue("Global", _global);
		}

	}
}

